package com.jinzhi.jzweb.controller;


import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.ValidUtils;
import com.jinzhi.jzsynthesize.ExcelVo.FeedbackVo;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ArchivesVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.service.ExaminationBatchService;
import com.jinzhi.jzweb.service.ExaminationCostService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.service.ArchivesService;
import com.jinzhi.common.utils.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2021-07-21 16:50:07 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/archives")
public class ArchivesController extends BaseController {
	@Autowired
	private ArchivesService archivesService;
	@Autowired
	private UserService userService;

	@Autowired
	private ExaminationCostService examinationCostService;

	@Autowired
	private
	@GetMapping()
	@RequiresPermissions("jzweb:archives:archives")
	String Archives(){
		//return "jzweb/archives/archives";

		return "jzweb/archives/archedit";
	}


	/**
	 * 考试调度信息导入
	 *
	 */
	@Log("考试调度信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:archives:import")
	public Result<?> importExcel(HttpServletRequest req, @RequestParam("feedbackFiles") MultipartFile feedbackFiles) {
		//---------------------------------检测导入信息及条件-----------------------------------------

		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(feedbackFiles.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<ArchivesVo> list = EasyPoiUtil.importExcel(feedbackFiles, 0, 1, ArchivesVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}

		//第三步--判断导入人员身份，获取导入人员信息
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<ArchivesDO> upDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getSchoolName())) {
				sb.append("第" + (i + startRow) + "行学校名称，请完善！" + ";");
			} else {
				if (StringUtils.isBlank(list.get(i).getProvince())) {
					sb.append("第" + (i + startRow) + "行所属省份，请完善！" + ";");
				} else {
				}
				if (sb.length() > 0) {
					ErrorCodeVo errorCodeVo = new ErrorCodeVo();
					errorCodeVo.setSeq(cout);
					cout += 1;
					errorCodeVo.setErrorCode(sb.toString());
					list1.add(errorCodeVo);
				}
				ArchivesDO archivesDO=new ArchivesDO();
				archivesDO.setSchoolName(list.get(i).getSchoolName());
				archivesDO.setUnitPrice(new BigDecimal(list.get(i).getUnitPrice()));
				archivesDO.setProvince(list.get(i).getProvince());
				archivesDO.setUpdateTime(new Date());
				Map map=new HashMap();
				map.put("name",list.get(i).getSchoolName());
				List<Map> listarc =archivesService.listArchives(map);
				if(listarc.size()==0){
					upDOList.add(archivesDO);
				}

			}
		}
			if (list1.size() == 0) {
				boolean c = archivesService.insertBatch(upDOList, upDOList.size());
				if (c) {
					return Result.ok("成功导入" + upDOList.size() + "条数据");
				} else {
					return Result.fail("考试调度信息添加错误，请稍后重试或联系管理员");
				}
			} else {

				JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
				//将list1存到缓存中
				EhCacheUtil.put("test12" + this.getUserId(), jsonArray);
				return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
			}
	}
	/**
	 * 考试调度信息导入
	 *
	 */
	@Log("考试调度信息导入")
	@PostMapping("/importLoad")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:archives:import")
	public Result<?> importLoad() {


//		//第二步--解析文件获得数据
//		List<ArchivesVo> list = EasyPoiUtil.importExcel(feedbackFiles, 0, 1, ArchivesVo.class);
//		if (list.size() == 0) {
//			return Result.fail("Excel数据为空，请完善");
//		}

		//第三步--判断导入人员身份，获取导入人员信息
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<ArchivesDO> upDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		EntityWrapper<ExaminationCostDO> entityWrapper = new EntityWrapper<>();
		entityWrapper.groupBy("org_name");
		List <ExaminationCostDO> list=	examinationCostService.selectList(entityWrapper);

			for (int i = 0; i < list.size(); i++) {
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值

				ArchivesDO archivesDO=new ArchivesDO();
				archivesDO.setSchoolName(list.get(i).getOrgName());
				archivesDO.setUnitPrice(new BigDecimal(list.get(i).getPriceStandard()));
				archivesDO.setProvince(list.get(i).getProvince());
				archivesDO.setUpdateTime(new Date());


				Map map=new HashMap();
				map.put("name",list.get(i).getOrgName());
				List<Map> listarc =archivesService.listArchives(map);

				if(listarc.size()==0){
					upDOList.add(archivesDO);
				}

			}

		if (list1.size() == 0) {
			if(upDOList.size()==0){
				return Result.ok("数据刷新成功" );
			}
			boolean c = archivesService.insertBatch(upDOList, upDOList.size());
			if (c) {
				return Result.ok("成功导入" + upDOList.size() + "条数据");
			} else {
				return Result.fail("考试调度信息添加错误，请稍后重试或联系管理员");
			}
		} else {

			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("test212" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
	}
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:archives:archives")
	public Result<Page<ArchivesDO>> list(ArchivesDO archivesDTO){
		// 查询列表数据
		Wrapper<ArchivesDO> wrapper = new EntityWrapper<ArchivesDO>().orderBy("id", false);
		if (archivesDTO.getSchoolName()!= null&&!archivesDTO.getSchoolName().equals("")) {
			wrapper.eq("school_name", archivesDTO.getSchoolName());
		}
		Page<ArchivesDO> page = archivesService.selectPage(getPage(ArchivesDO.class),wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				ArchivesDO obj = (ArchivesDO) page.getRecords().get(i);
		//UserDO userDO= userService.getByUserId(Long.valueOf(obj.getPerson()));
		//	obj.setPersonNmae(userDO.getName());
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("jzweb:archives:add")
	String add(String id,Model model){
		model.addAttribute("schId", id);
		return "jzweb/archives/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:archives:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ArchivesDO archives = archivesService.selectById(id);
		model.addAttribute("archives", archives);
		return "jzweb/archives/edit";
		// return "archivesedit";
	}
	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:archives:add")
	public Result<String> save( ArchivesDO archives){

//		if (!checkBankCard(archives.getBankAccount())){
//			return Result.fail("银行卡号信息有误！");
//		}

		Wrapper<ArchivesDO> wrapper = new EntityWrapper<ArchivesDO>();
		wrapper.eq("school_name", archives.getSchoolName());
		List list=	archivesService.selectList(wrapper);
		if(list.size()>0){
			return Result.fail("学校名称已存在！");
		}
		wrapper =new EntityWrapper<ArchivesDO>();
		wrapper.eq("bank_account",archives.getBankAccount());
		List<ArchivesDO> archivesDOS = archivesService.selectList(wrapper);
		if(list.size()>0){
			return Result.fail("银行卡号重复！");
		}
		archives.setUpdateTime(new Date());
		archivesService.insert(archives);
        return Result.ok();
	}


	/**
	 * 校验银行卡号方法
	 * @param bankCard
	 * @return
	 */
	public boolean checkBankCard(String bankCard) {
		if(bankCard.length() < 15 || bankCard.length() > 19) {
			return false;
		}
		char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
		if(bit == 'N'){
			return false;
		}
		return bankCard.charAt(bankCard.length() - 1) == bit;
	}



	/**
	 * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
	 * @param nonCheckCodeBankCard
	 * @return
	 */
	public char getBankCardCheckCode(String nonCheckCodeBankCard){
		if(nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0
				|| !nonCheckCodeBankCard.matches("\\d+")) {
			//如果传的不是数据返回N
			return 'N';
		}
		char[] chs = nonCheckCodeBankCard.trim().toCharArray();
		int luhmSum = 0;
		for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
			int k = chs[i] - '0';
			if(j % 2 == 0) {
				k *= 2;
				k = k / 10 + k % 10;
			}
			luhmSum += k;
		}
		return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
	}



	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:archives:edit")
	public Result<String>  update( ArchivesDO archives){
		boolean update = archivesService.updateById(archives);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:archives:remove")
	public Result<String>  remove( Long id){
		archivesService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:archives:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		archivesService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	@GetMapping("/archList")
	@RequiresPermissions("jzweb:archives:archList")
	String archList(){
		return "jzweb/archives/archivesFollowList";
	}

}
